$(function() {

	$.jcmsRepertory || (function($) {
		var dlgdom = $('#jcms-repertory-choose-dlg')
		// 搜索文件类型
		var searchType = $('#jcmsrcd-search-type');
		var searchLabel = $('#jcmsrcd-search-label_id');
		var searchFilename = $('#jcmsrcd-search-filename');
		var paginationdom = $('#jcmsrcd-repertory-pagination');
		var msgtext = $('#jcmsrcd-msgtext');
		var rechoosebutton = $('#jcmsrcd-rechoose');
		// 选中后的 class 名称
		var chooseCurClassName = "cur";

		// 初始化标签box
		searchLabel.combobox({
			width: 180,
			valueField: 'id',
			multiple: true,
			textField: 'name',
			label: '标签：',
			labelWidth: 50,
			panelHeight: 200,
			labelAlign: 'right',
			data: [{
				id: '-1',
				name: '全部'
			}]
		});

		// 通过公共数据获取资源标签数据
		globalData.repertoryLabelInfos(function(data) {
			var options = searchLabel.combobox('options');
			var list = options.data;
			if (data && data.rows && data.rows.length > 0) {
				for (var i in data.rows) {
					var item = data.rows[i];
					list.push(item)
				}
			}
			options.data = list
			options.onChange = function(newValue) {
				var list = newValue.filter(element => {
					if (parseInt(element) === -1) {
						return false;
					}
					return true;
				});
				if (!list || list.length < 1) {
					list = ['-1'];
				}
				searchLabel.combobox('setValues', list);
			}
			searchLabel.combobox(options);
		});

		// 定义资源类型box
		searchType.combobox({
			width: 220,
			multiple: true,
			valueField: 'id',
			textField: 'name',
			label: '类型：',
			labelWidth: 50,
			panelHeight: 200,
			labelAlign: 'right',
			data: [
				{ id: '-1', name: '全部' },
				{ id: '1', name: '图片' },
				{ id: '2', name: '文件' },
				{ id: '3', name: 'Flash' },
				{ id: '4', name: '音频' },
				{ id: '5', name: '视频' },
				{ id: '6', name: '外链图片' }
			],
			onChange: function(newValue) {
				var list = newValue.filter(element => {
					if (parseInt(element) === -1) {
						return false;
					}
					return true;
				});
				if (!list || list.length < 1) {
					list = ['-1'];
				}
				searchType.combobox('setValues', list);
			}
		});

		// 分页
		paginationdom.pagination({
			total: 0,
			showPageList: false,
			showPageInfo: false,
			showRefresh: false,
			pageNumber: 1,
			pageSize: 12,
			onSelectPage: function() {
				dlgObj.load();
			}
		});

		// 构建对象
		var dlgObj = {
			dlgdom: dlgdom,
			searchType: searchType,
			searchLabel: searchLabel,
			searchFilename: searchFilename,
			// 可选数量
			num: -1,
			choose: [],
			show: function() {
				dlgdom.dialog('open');
			},
			hide: function() {
				dlgdom.dialog('close');
			},
			load: function() {
				// 查询资源数据
				var param = {
					filename: $.trim(searchFilename.textbox('getValue')),
					label_id: searchLabel.combobox('getValues').join(","),
					type: searchType.combobox('getValues').join(","),
					is_refuse: 0,
					page: paginationdom.pagination('options').pageNumber,
					rows: paginationdom.pagination('options').pageSize
				};

				globalData.repertoryInfos(param, function(data) {
					if (data && data.rows && data.rows.length > 0) {
						// 有数据的情况下进行渲染
						reloadReperotyRender(data.rows)
						pepertoryTempData = data.rows
					} else {
						reloadReperotyRenderEmpty()
					}
					if (data.total > 12) {
						paginationdom.show();
						var options = paginationdom.pagination('options');
						options.total = parseInt(data.total);
						paginationdom.pagination(options);
					} else {
						paginationdom.hide();
					}
				});
			},
			callback: function() { }
		}

		var pepertoryTempData = null

		// 定义jQuery插件
		$.extend({
			jcmsRepertory: function(obj) {
				var param = Object.assign({}, {
					total: 1,
					type: [],
					choose: function() { }
				}, obj)

				dlgObj.num = param.total;
				if (param.type.length === 0) {
					searchType.combobox({
						disabled: false
					});
					searchType.combobox('setValues', [-1]);
				} else {
					searchType.combobox({
						disabled: true
					});
					searchType.combobox('setValues', param.type);
				}
				paginationdom.pagination('select', 1);
				searchFilename.textbox('setValue', '');
				searchLabel.combobox('setValue', '-1');
				dlgObj.choose = [];
				dlgObj.callback = param.choose

				jcmsrcdMsgtext();
				dlgObj.load();
				return dlgObj;
			}
		});

		dlgdom.find('.search-item .searchdata').on('click', function() {
			paginationdom.pagination('select', 1);
		});

		dlgdom.find('.search-item .resetdata').on('click', function() {
			searchFilename.textbox('setValue', '');
			searchLabel.combobox('setValue', '-1');
			searchType.combobox('setValue', '-1');
		});

		$('#jcms-repertory-choose-sure').on('click', function() {
			dlgObj.callback(dlgObj.choose);
			dlgdom.dialog('close');
		});

		rechoosebutton.on('click', function() {
			dlgObj.choose = [];
			dlgdom.find('#jcmsrcd-main-gallery #jcmsrcd-gallery .cur').each(function() {
				$(this).removeClass("cur");
			});
		});

		// =========================== 方法 区域 ==============================
		// 渲染空数据
		function reloadReperotyRenderEmpty() {
			$('#jcmsrcd-gallery').html('');
			var html = '<div class="empty" style="height: 40px;position: relative;margin: 200px auto;font-size: 16px;color: #858585;">未查询到数据！</div>';
			$('#jcmsrcd-gallery').html(html);
		}

		// 渲染数据列表
		function reloadReperotyRender(rows) {
			$('#jcmsrcd-gallery').html('');
			var html = '';
			for (var i in rows) {
				var item = rows[i];
				var ite = dlgObj.choose.find(ele => {
					return parseInt(ele.id) === parseInt(item.id)
				});
				html += '<li data-id="' + item.id + '"><div class="item' + (ite ? ' cur' : '') + '">';
				html += '<div class="image-box">';

				if (parseInt(item.type) === 0 || parseInt(item.type) === 6) {
					html += '<a href="' + item.imageSrc + '" class="img-a lery" title="' + item.originalFilename + '">';
					html += '<img src="' + item.imageSrc + '" class="image">';
					html += '</a>';
				} else {
					html += '<a class="img-a" title="' + item.originalFilename + '">';
					html += '<img src="' + item.imageSrc + '" class="image">';
					html += '</a>';
				}
				html += '</div>';
				html += '<div class="infos">';
				html += '<span class="title">' + item.originalFilename + '</span>';
				html += '<div class="labdes" style="padding-bottom: 4px;">';
				html += '<a class="label" href="javascript:void(0)" data-labelid="' + item.labelId + '" style="color: #337ab7;">标签</a>';
				html += '<span>';
				html += '<a class="des" href="javascript:void(0)" style="color: #337ab7;">属性</a>';
				html += '</span>';
				html += '</div>';
				html += '</div>';
				html += '</div></li>';
			}

			$('#jcmsrcd-gallery').html(html);
			// 渲染完成后
			// 灯箱效果
			$('#jcmsrcd-gallery .image-box .lery').rebox();

			// 显示完整标题
			$('#jcmsrcd-gallery .item .infos .title').each(function() {
				$(this).tooltip({
					position: 'top',
					content: $(this).html(),
				});
			})

			// 显示详情
			$('#jcmsrcd-gallery .item .infos .labdes .des').each(function(index) {
				var item = rows[index];
				var content = '';
				if (parseInt(item.type) === 6) {
					content += '<div style="padding:2px 4px;">类型：外部链接图片</div>';
				} else if (parseInt(item.type) === 1) {
					content += '<div style="padding:2px 4px;">类型：图片</div>';
					content += '<div style="padding:2px 4px;">大小：' + func.makeByteSizeUnit(item.size) + '</div>';
					content += '<div style="padding:2px 4px;">尺寸：' + item.pixel + '</div>';
				} else if (parseInt(item.type) === 2) {
					content += '<div style="padding:2px 4px;">类型：文件</div>';
					content += '<div style="padding:2px 4px;">大小：' + func.makeByteSizeUnit(item.size) + '</div>';
				} else if (parseInt(item.type) === 3) {
					content += '<div style="padding:2px 4px;">类型：Flash</div>';
					content += '<div style="padding:2px 4px;">大小：' + func.makeByteSizeUnit(item.size) + '</div>';
				}
				else if (parseInt(item.type) === 4) {
					content += '<div style="padding:2px 4px;">类型：视频</div>';
					content += '<div style="padding:2px 4px;">大小：' + func.makeByteSizeUnit(item.size) + '</div>';
				} else if (parseInt(item.type) === 5) {
					content += '<div style="padding:2px 4px;">类型：音频</div>';
					content += '<div style="padding:2px 4px;">大小：' + func.makeByteSizeUnit(item.size) + '</div>';
				} else {
					console.log(item)
					return;
				}
				content += '<div style="padding:2px 4px;">创建时间：' + moment(item.createdAt).format('YYYY-MM-DD') + '</div>';
				$(this).tooltip({
					position: 'bottom',
					content: content,
				});
			});

			// 显示标签
			$('#jcmsrcd-gallery .item .infos .labdes .label').each(function() {
				var _this = $(this);
				var labelId = _this.data('labelid');
				globalData.repertoryLabelInfos(function(labeles) {
					var item = labeles.rows.find(ele => {
						return parseInt(ele.id) === parseInt(labelId);
					});
					var name = "无";
					if (item) {
						name = item.name;
					}
					_this.tooltip({
						position: 'bottom',
						content: name,
					});
				});
			});

			// 点击选中图片
			dlgdom.find('#jcmsrcd-main-gallery #jcmsrcd-gallery .item').on('click', function() {
				if (dlgObj.num < 1) {
					return;
				}
				var len = dlgObj.choose && dlgObj.choose.length ? dlgObj.choose.length : 0;
				var _this = $(this);
				if (_this.hasClass(chooseCurClassName)) {
					_this.removeClass(chooseCurClassName);
					repertoryChoose(0, _this)
				} else {
					if (len >= dlgObj.num) {
						mylayer.error("已选中" + len + "个资源，总共可以选择" + dlgObj.num + "个资源");
						return;
					}
					_this.addClass(chooseCurClassName);
					repertoryChoose(1, _this)
				}
				jcmsrcdMsgtext();
			});
		}

		// 选中
		function repertoryChoose(n, itemDom) {
			var id = itemDom.parents('li').data('id');
			if (!id || isNaN(parseInt(id))) {
				return;
			}
			var repertory = pepertoryTempData.find(ele => {
				return parseInt(ele.id) === parseInt(id)
			})
			if (!repertory) {
				return;
			}
			repertory = JSON.parse(JSON.stringify(repertory))
			if (n) {
				// 加
				dlgObj.choose.push(repertory)
			} else {
				// 减
				if (!dlgObj.choose || dlgObj.choose.length < 1) {
					return;
				}
				var index = dlgObj.choose.findIndex(ele => {
					return parseInt(ele.id) === parseInt(repertory.id)
				})
				if (index >= 0) {
					dlgObj.choose.splice(index, 1);
				}
			}

			if (dlgObj.choose && dlgObj.choose.length > 0) {
				rechoosebutton.show();
			} else {
				rechoosebutton.hide();
			}
		}

		function jcmsrcdMsgtext() {
			var num = dlgObj.num;
			var html = "";
			if (num < 1) {
				html = "<span style=\"color:red;\">未初始化选择资源数</span>";
			} else {
				var len = dlgObj.choose && dlgObj.choose.length ? dlgObj.choose.length : 0;
				html = "已选中" + len + "个资源，总共可以选择" + num + "个资源";
			}
			msgtext.html(html);
		}
	})(jQuery);
});